﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Net;
using System.Data;

namespace SimpleService.MVC
{
    public class MvcUtility
    {

        public static string ReadFile(string filename)
        {
            string content = "";

            StreamReader sr = new StreamReader(filename, Encoding.Default);
            content = sr.ReadToEnd();
            sr.Close();

            return content.Trim();

        }


        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>是否存在</returns>
        public static bool FileExists(string filename)
        {
            return System.IO.File.Exists(filename);
        }

        /// <summary>
        /// 獲得目前絕對路徑
        /// </summary>
        /// <param name="strPath">指定的路徑</param>
        /// <returns>絕對路徑</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }




        /// <summary>
        /// 檢測是否是正確的Url
        /// </summary>
        /// <param name="strUrl">要驗證的Url</param>
        /// <returns>判斷結果</returns>
        public static bool IsURL(string strUrl)
        {
            return Regex.IsMatch(strUrl, @"^(http|https)\://([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{1,10}))(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\?\'\\\+&%\$#\=~_\-]+))*$");
        }

        /// <summary>
        /// 檢測是否有Sql危險字符
        /// </summary>
        /// <param name="str">要判斷字符串</param>
        /// <returns>判斷結果</returns>
        public static bool IsSafeSqlString(string str)
        {

            return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
        }

        //檢查目前頁面的完整物理路徑之 檔案存在否
        public static bool FileExists()
        {
            try
            {
                //若檔案不存在則false
                if (!File.Exists(HttpContext.Current.Request.PhysicalPath.ToString()))
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }





        /// <summary>
        /// 是空
        /// </summary>
        /// <param name="字串"></param>
        /// <returns></returns>
        public static bool IsNull(string s)
        {
            string output = "" + s;

            if (output.Trim() == "" || output == null || output == "0")
            {
                return true;
            } //end if
            else
            {
                return false;
            } //end else

        } //end IsNull



        //是否有隱碼
        public static bool IsSafeRequest(Page p)
        {
            bool output = true;
            foreach (string var in p.Request.QueryString)
            {
                output = IsSafeSqlString(p.Request.QueryString[var]);
                if (!output) return output;
            }
            return output;
        }

        /// <summary>
        /// 清理字符串
        /// </summary>
        public static string CleanInput(string strIn)
        {
            return Regex.Replace(strIn.Trim(), @"[^\w\.@-]", "");
        }



        /// <summary>
        /// 根據Url獲得源文件內容
        /// </summary>
        /// <param name="url">合法的Url地址</param>
        /// <returns></returns>
        public static string GetSourceTextByUrl(string url)
        {
            WebRequest request = WebRequest.Create(url);
            request.Timeout = 20000;//20秒超時
            WebResponse response = request.GetResponse();

            Stream resStream = response.GetResponseStream();
            StreamReader sr = new StreamReader(resStream);
            return sr.ReadToEnd();
        }


        public static void ToXml(DataTable dt, HttpResponse response) 
        {
            response.ContentType = "application/xml";    //用 application/xml 而不用  text/xml 解釋如於  Utility.cs 中
            response.Write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
            dt.WriteXml(response.OutputStream);
        }

    }
}
